<template>
    <div class="container">
        <div class="header">
            <div class="nav-item" @click="handleLoadModel">倾斜模型</div>
            <div class="nav-item" @click="handleLoadShp">shp数据</div>
            <div class="drag-zone">
                <span>{{appTitle}}</span>
                <span v-if="appSubTitle"> - {{appSubTitle}}</span>
            </div>
            <div class="window-action">
                <span @click="handleWinMin" class="iconfont icon-suoxiao"></span>
                <span @click="handleWinMax" :class="'iconfont icon-' + (isMaximized ? 'huanyuan' : 'fangda')"></span>
                <span @click="handleWinClose" class="iconfont icon-close"></span>
            </div>
        </div>
        <div class="section">
            <div id="cesiumViewer"></div>
            <div id="credit"></div>
            <template v-if="dataList.length > 0">
                <div class="drag-content" ref="dragContentRef" v-drag="dragInit">
                    <div class="drag-header">资源目录</div>
                    <div class="drag-body">
                        <div class="data-list" @click="handleDataItemClick(entity)" v-for="entity in dataList" :key="entity.id">
                            <span>{{entity.typeTxt}} </span>
                            <strong :title="entity.name">{{entity.name}}</strong>
                        </div>
                    </div>
                </div>
            </template>
        </div>
    </div>
</template>
<script setup lang="ts">
import { onMounted,ref, nextTick } from 'vue'
import * as Cesium from 'cesium'
import { ElMessage} from 'element-plus'
import { initCesium } from '@utils/cesumUtil' 
import useDirectiveHook from '@hooks/useDirectiveHook'
import { loadTdtImagery, loadTdtCia, generateRandomId } from '@utils/index'
import Primitives from '@entity/Primitives'
import GeojsonWorker from '@workers/GeojsonWorker.js?worker'
const { directoryOpen, fileOpen, windowClose, windowMax,windowMin } = window.eleApi
const { vDrag } = useDirectiveHook()
enum DataEntityType {
    Model = '1',
    Shp = '2',
    ModelTxt = '倾斜模型',
    ShpTxt = 'shp数据'
}

type DataEntity = {
    type: DataEntityType.Model | DataEntityType.Shp
    typeTxt: DataEntityType.ModelTxt | DataEntityType.ShpTxt
    name:string
    fullPath:string
    id:string
}
//应用标题
const appTitle = ref('cesium应用程序')
//应用副标题
const appSubTitle = ref('')

let isMaximized = ref(false)

const shpLoad = (window as any).shp

const dragInit = ref({
    top: 50, 
    right: 50
})
const dragContentRef = ref(null)

const dataList = ref<Array<DataEntity>>([])

let viewer:Cesium.Viewer|undefined = undefined

let globalTileset:Cesium.Cesium3DTileset | undefined = undefined

onMounted(async () => {
    viewer = await initCesium()
    //加载天地图影像
    viewer.imageryLayers.addImageryProvider(loadTdtImagery())
    // //加载天地图标注
    // viewer.imageryLayers.addImageryProvider(loadTdtCia())
})  
//设置副标题

const handleSetSubTitle = (txt:string) => {
    appSubTitle.value = txt
}

//加载模型数据（）
const handleLoadModel = async () => {
    let dir = await directoryOpen()
    if (!dir) return
    let path = dir!.replace(/\\/g, '//')
    let name = path.substring(path.lastIndexOf('/') + 1)
    let fullPath = `${path}//tileset.json`
    if (globalTileset) {
        viewer!.scene.primitives.remove(globalTileset)
    }  
    globalTileset = new Cesium.Cesium3DTileset({url: fullPath})   
    globalTileset.readyPromise.then(tileset => {
        viewer!.scene.primitives.add(tileset)
        viewer!.flyTo(tileset)
        if (dataList.value.findIndex(({fullPath:_path}) => fullPath == _path) < 0) {
            dataList.value.push({
                name, 
                typeTxt: DataEntityType.ModelTxt,
                fullPath, id: generateRandomId(), type: DataEntityType.Model
            }) 
        } 
        handleSetSubTitle(`（${DataEntityType.ModelTxt}）${name}`)
    }).catch(() => {
        ElMessage.warning('模型加载错误')
    })
}

// 模型加载方法
const modelLoadFn = (path:string) => {
    if (globalTileset) {
        viewer!.scene.primitives.remove(globalTileset)
    }
    globalTileset = new Cesium.Cesium3DTileset({url: path})   
    globalTileset.readyPromise.then(tileset => {
        viewer!.scene.primitives.add(tileset)
        viewer!.flyTo(tileset)
    }).catch(() => {
        ElMessage.warning('模型加载错误')
    })
}

//资源列表点击
const handleDataItemClick = ({name, type, typeTxt, fullPath}: DataEntity) => {
    handleSetSubTitle(`（${typeTxt}）${name}`)
    switch (type) {
        case DataEntityType.Model:
            modelLoadFn(fullPath)
        break;
        case DataEntityType.Shp: 
        break;
    }
}

//加载shp数据
const handleLoadShp = async () => {
    let shpPath = await fileOpen()
    if (!shpPath || !shpPath.endsWith('.shp')) {
        ElMessage.warning('请选择.shp文件')
        return
    }
    let dataSource:Cesium.DataSource|undefined
    let finalPath = shpPath.substring(0, shpPath.lastIndexOf('.'));
    if (viewer) {
        shpLoad(finalPath).then( async (json:any) => {
            try {
                const worker = new GeojsonWorker();
                worker.postMessage(json)
                worker.onmessage = ({data}) => {
                    const primitives = new Primitives(data)
                    primitives.create(viewer!)
                    worker.terminate()
                }
            } catch {
                
            }
        }).catch(() => {
            ElMessage.warning('shp数据加载错误')
        })
    } else {
        ElMessage.warning('三维球体未初始化')
    }
}

const handleWinMin = windowMin
const handleWinMax = async () => {
    isMaximized.value = await windowMax()
    if (!isMaximized.value && dragContentRef.value) {
        nextTick(() => { 
            (dragContentRef.value as any).style.top = `${dragInit.value.top}px`;
            (dragContentRef.value as any).style.right = `${dragInit.value.right}px`;
            (dragContentRef.value as any).style.left = 'auto';
            (dragContentRef.value as any).style.bottom = 'auto';
        })
    }
}
const handleWinClose = windowClose



</script>
<style lang="scss" scoped>
    $themeBackground: rgba(23, 24, 43, 1);
    .container{
        width: 100vw;
        height: 100vh;
        background-color: $themeBackground;
        padding: 0 4px 4px;
        border-top: none;
        box-sizing: border-box;
        .header{
            width: 100%;
            height: 32px;
            display: flex;
            .nav-item{
                height: 32px;
                color: #bbb;
                text-align: center;
                line-height: 32px;
                font-size: 14px;
                cursor: pointer;
                padding: 0 4px;
                flex-shrink: 0;
                &:hover{
                    color: #fff;
                }
            }
            .drag-zone{
                width: 100%;
                height: 32px;
                color: #bbb;
                line-height: 32px;
                font-size: 14px;
                -webkit-app-region: drag;
                user-select: none;
                text-align: center;
                box-sizing: border-box;
            }
            .window-action{
                width: 96px;
                flex-shrink: 0;
                height: 32px;
                display: flex;
                line-height: 32px;
                color: #bbb;
                .iconfont{
                    width: 32px;
                    text-align: center;
                    &:hover{
                        color: #fff;
                    }
                }
            }
        }
        .section{
            width: 100%;
            height: calc(100% - 32px);
            position: relative;
            .drag-content{
                width: 300px;
                background-color: $themeBackground;
                border-radius: 4px;
                padding: 0 4px 4px;
                .drag-header{
                    width: 100%;
                    height: 32px;
                    line-height: 32px;
                    color: #fff;
                    text-indent: 16px;
                }
                .drag-body{
                    width: 100%;
                    background-color: #fff;
                    padding: 10px;
                    box-sizing: border-box;
                    .data-list{
                        width: 100%;
                        height: 38px;
                        line-height: 38px;
                        cursor: pointer;
                        position: relative;
                        text-overflow: ellipsis;
                        overflow: hidden;
                        white-space: nowrap;
                        span{
                            font-size: 12px;
                            border: 1px solid $themeBackground;
                            padding: 2px 4px;
                            border-radius: 4px;
                            margin-right: 4px;
                        }
                        strong{
                            font-size: 14px;
                        }
                        &::before{
                            position: absolute;
                            bottom: 0;
                            left: 0;
                            width: 0;
                            height: 1px;
                            content: "";
                            background-color: $themeBackground;
                            transition: all .2s ease-in;
                        }
                        &:hover{
                            &::before{
                                width: 100%;
                            }
                        }
                    }
                }
            }
            #credit{display: none;}
            #cesiumViewer{
                width: 100%;
                height: 100%;
            }
        }
    }
</style>